const mysql = require('../db/mysql')
const roleService = require('../service/roleService')


// 查询角色列表
exports.getRoleList = function (req, res) {
    let { roleName, roleDesc, page } = req.query
    roleName = `%${roleName}%`
    roleDesc = `%${roleDesc}%`
    mysql.query(roleService.roleList, [roleName, roleDesc, (page - 1) * 10]).then((data) => {
        mysql.query(roleService.totalCount, [roleName, roleDesc]).then((total) => {
            const jsonData = JSON.parse(JSON.stringify(data))
            res.json({
                code: 0,
                total: total[0].total,
                data: jsonData,
            })
        })
    })
}

// 新增角色
exports.addRole = function (req, res) {
    let { roleName, roleRemark, roleDesc, menu } = req.body
    mysql.query(roleService.findExists, roleName).then((exists) => {
        const existsList = JSON.parse(JSON.stringify(exists))
        if(existsList.length) {
            res.json({
                code: 1,
                message: '关键字已存在',
            })
        } else {
            const menuStr = JSON.stringify(menu)
            mysql.query(roleService.addRole, [roleName, roleRemark, roleDesc, menuStr]).then((data) => {
                const jsonData = JSON.parse(JSON.stringify(data))
                res.json({
                    code: 0,
                    data: jsonData[0],
                })
            })
        }
    })
}

// 编辑角色
exports.editRole = function (req, res) {
    let { roleName, roleRemark, roleDesc, menu, id } = req.body
    const menuStr = JSON.stringify(menu)
    mysql.query(roleService.editRole, [roleName, roleRemark, roleDesc, menuStr, id]).then((data) => {
        const jsonData = JSON.parse(JSON.stringify(data))
        res.json({
            code: 0,
            data: jsonData[0],
        })
    })
}

// 删除角色
exports.deleteRole = function (req, res) {
    let { id } = req.body
    mysql.query(roleService.deleteRole, id).then((data) => {
        const jsonData = JSON.parse(JSON.stringify(data))
        res.json({
            code: 0,
            data: jsonData[0],
        })
    })
}

// 获取登录用户拥有的所有角色及对应的菜单权限
exports.userRole = function (req, res) {
    let { roles } = req.body
    mysql.query(roleService.userRole, [roles]).then((data) => {
        const jsonData = JSON.parse(JSON.stringify(data))
        res.json({
            code: 0,
            data: jsonData,
        })
    })
}
